package com.ruoyi.ams.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.ams.domain.*;
import com.ruoyi.ams.domain.vo.AssetFullInfoAddVo;
import com.ruoyi.ams.domain.vo.AssetFullInfoEditVo;
import com.ruoyi.ams.domain.vo.AssetResovleRecordVo;
import com.ruoyi.ams.domain.vo.ReturnDataVo;
import com.ruoyi.ams.service.*;
import com.ruoyi.common.core.domain.AsmsAssetFullInfo;
import com.ruoyi.common.core.domain.AssetInfoView;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.SysFile;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.AmsAssetInfo;
import com.ruoyi.common.core.domain.model.AmsAssetTemplate;
import com.ruoyi.common.core.domain.model.AmsOwnAsset;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.rabbitmq.constant.RabbitmqConstants;
import com.ruoyi.common.rabbitmq.domain.EmailNotifyTemplate;
import com.ruoyi.common.rabbitmq.utils.NotifyUtils;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.security.service.TokensService;
import com.ruoyi.file.controller.SysFileController;
import com.ruoyi.system.controller.SysDeptController;
import com.ruoyi.system.controller.SysUserController;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import com.ruoyi.asms.service.IAsmsAssetFullInfoService;
/**
 * 资产详细信息Controller
 *
 * @author yfkj
 * @date 2021-10-19
 */
@RestController
@RequestMapping("/ams/AssetInfoView")
public class AssetInfoViewController extends BaseController {

    @Autowired
    private IAssetInfoViewService assetInfoViewService;
    @Autowired
    private IAmsAssetTemplateService amsAssetTemplateService;
    @Autowired
    private IAmsAssetInfoService amsAssetInfoService;
    @Autowired
    private AmsReusingService amsReusingService;
    @Autowired
    private IAmsOwnAssetService amsOwnAssetService;

    @Autowired
    private IAsmsAssetFullInfoService assetFullInfoService;

    @Autowired
    private TokensService tokenService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IAmsAssetRequisitionService assetRequisitionService;
    @Autowired
    private IAmsAssetBorrowService assetBorrowService;
    @Autowired
    private IAmsAssetAllocationService assetAllocationService;
    @Autowired
    private IAmsAssetInfoChangeService assetInfoChangeService;
    @Autowired
    private IAmsAssetMaintenanceRecordService assetMaintenanceRecordService;
    @Autowired
    private IAmsAssetRepairRecordService assetRepairRecordService;
    @Autowired
    private IAmsAssetScrapService assetScrapService;
    @Autowired
    private IAmsAssetInventoryService assetInventoryService;
    @Autowired
    private IAmsAssetTypeService amsAssetTypeService;
    @Autowired
    private IAmsOwnAddressService amsOwnAddressService;
    @Autowired
    private IAmsAssetAllocationDetailService assetAllocationDetailService;
    @Autowired
    private IAmsAssetInfoChangeDetailService assetInfoChangeDetailService;
    @Autowired
    private IAmsAssetRepairRecordDetailService assetRepairRecordDetailService;
    @Autowired
    private IAmsAssetScrapDetailService assetScrapDetailService;
//    @Autowired
//    private RemoteDeptService remoteDeptService;
//    @Autowired
//    private RemoteUserService remoteUserService;
//    @Autowired
//    private RemoteFileService remoteFileService;
    @Autowired
    private SysDeptController deptController;
    @Autowired
    private SysUserController userController;
    @Autowired
    private SysFileController fileController;

    /**
     * 查询资产详细信息列表
     */
    //@PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AssetInfoView:list")
    @GetMapping("/list")
    @ApiOperation("资产列表信息，按3个维度展示：1、资产基本信息（名称、型号、类型、编码、品牌、批次）。\n" +
            "2、资产所有方信息(所有方使用部门、使用人员、位置、状态、时间信息)。\n" +
            "3、资产维护方信息(维护方售后维护模块开发后再做)")
    public TableDataInfo list(AssetInfoView assetInfoView) {

        QueryWrapper<AssetInfoView> wrapper = new QueryWrapper<>();
        if (assetInfoView.getAssetStatus() != null) {
            wrapper.eq(AssetInfoView.ASSET_STATUS, assetInfoView.getAssetStatus());
        }
        if (assetInfoView.getUseDeptId() != null) {
            wrapper.eq(AssetInfoView.USE_DEPT_ID, assetInfoView.getUseDeptId());
        }
        if (StringUtils.isNotEmpty(assetInfoView.getAssetCode())) {
            wrapper.like(AssetInfoView.ASSET_CODE, assetInfoView.getAssetCode());
        }
        if (StringUtils.isNotEmpty(assetInfoView.getAssetTypeName())) {
            wrapper.like(AssetInfoView.ASSET_TYPE_NAME, assetInfoView.getAssetTypeName());
        }
        wrapper.orderByDesc(AssetInfoView.ASSET_ID);
        //系统管理员查看所有资产、部门负责人查看本部门拥有的资产
        Set<Long> userOwnDeptIds = tokenService.getUserOwnDeptIds();
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && userOwnDeptIds != null && userOwnDeptIds.size() > 0) {
            wrapper.in(AssetInfoView.OWN_DEPT_ID, userOwnDeptIds);
            startPage();
            List<AssetInfoView> list = assetInfoViewService.list(wrapper);
            return getDataTable(list);
        } else {
            startPage();
            List<AssetInfoView> lst = assetInfoViewService.list(wrapper);
            return getDataTable(lst);
        }
    }

    /**
     * 导出资产详细信息列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AssetInfoView:export")
    @Log(title = "资产详细信息", businessType = BusinessType.EXPORT)
    @PostMapping(value="/export", produces = "application/octet-stream")
    public void export(HttpServletResponse response, AssetInfoView assetInfoView) throws IOException {
        List<AssetInfoView> list = assetInfoViewService.selectAssetInfoViewList(assetInfoView);
        ExcelUtil<AssetInfoView> util = new ExcelUtil<AssetInfoView>(AssetInfoView.class);
        util.exportExcel(response, list, "资产详细信息数据");
    }

    /**
     * 新增资产详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AssetInfoView:add")
    @Log(title = "资产详细信息", businessType = BusinessType.INSERT)
    @PostMapping("/addFullAssetInfo")
    @ApiOperation("资产入库新增")
  //  @D@S("master")
    public AjaxResult addFullAssetInfo(@RequestBody AssetFullInfoAddVo assetFullInfoAddVo) {
        //处理数据
        AmsAssetInfo amsAssetInfo = new AmsAssetInfo();
        BeanUtils.copyProperties(assetFullInfoAddVo, amsAssetInfo);
        AmsOwnAsset amsOwnAsset = new AmsOwnAsset();
        BeanUtils.copyProperties(assetFullInfoAddVo, amsOwnAsset);
        if (assetFullInfoAddVo.getSn().length() > 20) {
            return AjaxResult.error("设备SN号超出最大长度：20位");
        }
        if (assetFullInfoAddVo.getAssetCode().length() > 20) {
            return AjaxResult.error("设备码超出最大长度：20位");
        }
        //向视图表对象插入数据
        AsmsAssetFullInfo assetFullInfo = amsReusingService.setAssetInfo(assetFullInfoAddVo);
        assetFullInfo.setBindUserId(SecurityUtils.getUserId());
        assetFullInfo.setBindUserName(SecurityUtils.getUsername());
        assetFullInfo.setBindTime(System.currentTimeMillis());
        assetFullInfo.setUpdateBy(SecurityUtils.getUsername());
        assetFullInfo.setUpdateTime(System.currentTimeMillis());
        R<SysDept> ownDept = deptController.getDeptById(assetFullInfo.getOwnDeptId());
        if (ownDept.getCode() == R.FAIL) {
            throw new ServiceException(ownDept.getMsg());
        }
        assetFullInfo.setOwnDeptName(ownDept.getData().getDeptShortName());
        //如果是新增的型号
        if (assetFullInfoAddVo.getAssetTemplateId() == null) {
            AmsAssetTemplate amsAssetTemplate = new AmsAssetTemplate();
            BeanUtils.copyProperties(assetFullInfoAddVo, amsAssetTemplate);
            //去重检查
            AmsAssetTemplate exit = amsReusingService.findAmsAssetTemplate(amsAssetTemplate);
            if (exit == null) {
                amsAssetTemplateService.save(amsAssetTemplate);
                amsAssetInfo.setAssetTemplateId(amsAssetTemplate.getAssetTemplateId());
            } else {
                amsAssetInfo.setAssetTemplateId(exit.getAssetTemplateId());
            }
        }
        if (amsAssetInfo.getAssetCode() == null) {
            amsAssetInfo.setAssetCode(new Random(8).toString());
        }
        if (amsAssetInfo.getSn() == null) {
            amsAssetInfo.setSn(new Random(8).toString());
        }
        //去重检查
        AmsAssetInfo exitAmsAssetInfo = amsReusingService.findAmsAssetInfo(amsAssetInfo);
        if (exitAmsAssetInfo != null) {
            return AjaxResult.error("序列号或资产编码重复！");
        }
        amsAssetInfoService.save(amsAssetInfo);
        amsOwnAsset.setAssetId(amsAssetInfo.getAssetId());
        amsOwnAssetService.save(amsOwnAsset);
        assetFullInfo.setAssetId(amsAssetInfo.getAssetId());
        amsReusingService.saveAssetFullInfo(assetFullInfo);
        //第一步完成后返回数据供第二步使用
        ReturnDataVo dataVo = new ReturnDataVo();
        dataVo.setAssetId(amsAssetInfo.getAssetId());
        dataVo.setOwnDeptId(assetFullInfoAddVo.getOwnDeptId());
        //throw new GlobalException("尝试回滚");
        return AjaxResult.success(dataVo);
    }

    /**
     * 修改资产详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AssetInfoView:add")
    @Log(title = "资产详细信息", businessType = BusinessType.UPDATE)
    @PostMapping("/editFullAssetInfo")
    @ApiOperation("资产入库修改")
    //  @D@S("master")
    public AjaxResult editFullAssetInfo(@RequestBody AssetFullInfoEditVo assetFullInfoEditVo) {
        //通过assetId寻找ownAssetId
        AmsOwnAsset amsOwnAsset = amsOwnAssetService.getOne(new QueryWrapper<AmsOwnAsset>()
                .eq(AmsOwnAsset.ASSET_ID, assetFullInfoEditVo.getAssetId()), false);
        if (amsOwnAsset != null) {
            assetFullInfoEditVo.setOwnAssetId(amsOwnAsset.getOwnAssetId());
        }
        //如果是新增的型号
        if (assetFullInfoEditVo.getAssetTemplateId() == null) {
            AmsAssetTemplate amsAssetTemplate = new AmsAssetTemplate();
            BeanUtils.copyProperties(assetFullInfoEditVo, amsAssetTemplate);
            //去重检查
            AmsAssetTemplate exit = amsReusingService.findAmsAssetTemplate(amsAssetTemplate);
            if (exit == null) {
                amsAssetTemplateService.save(amsAssetTemplate);
                assetFullInfoEditVo.setAssetTemplateId(amsAssetTemplate.getAssetTemplateId());
            } else {
                assetFullInfoEditVo.setAssetTemplateId(exit.getAssetTemplateId());
            }
        }
        AmsAssetInfo oldAmsAssetInfo = amsAssetInfoService.getById(assetFullInfoEditVo.getAssetId());
        BeanUtils.copyProperties(assetFullInfoEditVo, oldAmsAssetInfo);
        AmsOwnAsset oldAmsOwnAsset = amsOwnAssetService.getById(assetFullInfoEditVo.getOwnAssetId());
        BeanUtils.copyProperties(assetFullInfoEditVo, oldAmsOwnAsset);
        QueryWrapper<AsmsAssetFullInfo> queryWrapper = new QueryWrapper<AsmsAssetFullInfo>()
                .eq(AsmsAssetFullInfo.ASSET_ID, assetFullInfoEditVo.getAssetId());

        AsmsAssetFullInfo oldAssetFullInfo = amsReusingService.getAssetFullInfo(queryWrapper);

        AsmsAssetFullInfo assetInfo = amsReusingService.setAssetInfo(assetFullInfoEditVo);
        if (oldAssetFullInfo != null) {
            assetInfo.setId(oldAssetFullInfo.getId());
        }
        //更新资产所有方的名字
        R<SysDept> ownDept = deptController.getDeptById(assetInfo.getOwnDeptId());
        if (ownDept.getCode() == R.FAIL) {
            throw new ServiceException(ownDept.getMsg());
        }
        assetFullInfoService.update(new UpdateWrapper<AsmsAssetFullInfo>()
                .set(AsmsAssetFullInfo.OWN_DEPT_NAME, ownDept.getData().getDeptShortName())
                .eq(AsmsAssetFullInfo.ASSET_ID, assetInfo.getAssetId()));
        assetInfo.setUpdateBy(SecurityUtils.getUsername());
        assetInfo.setUpdateTime(System.currentTimeMillis());

        amsAssetInfoService.updateById(oldAmsAssetInfo);
        amsOwnAssetService.updateById(oldAmsOwnAsset);
        assetFullInfoService.updateById(assetInfo);
        amsReusingService.updateFullInfo(assetInfo);
        //throw new GlobalException("尝试回滚");
        /**
         * 资产信息变更通知  使用部门所属部门  部门表邮箱  内容   SecurityUtils 某人 变更了 某地某类型资产信息
         */
        Long useDeptId = oldAssetFullInfo.getUseDeptId();
        Long ownDeptId = oldAssetFullInfo.getOwnDeptId();

        List<Long> deptIds = new LinkedList<>();
        deptIds.add(useDeptId);
        deptIds.add(ownDeptId);

        R<List<SysUser>> rDeptManegers = userController.getDeptManegersByDeptIds(deptIds);

        if(rDeptManegers != null  ){
            Set<Object> notifyUsers = new HashSet<>();
            if(rDeptManegers.getData() != null && rDeptManegers.getData().size() > 0){
                notifyUsers.addAll(rDeptManegers.getData());
            }

            StringBuilder content = new StringBuilder();

            content.append(SecurityUtils.getUsername());
            content.append(" 变更了 位于");
            content.append(oldAssetFullInfo.getAddressFullName());
            content.append("的");
            content.append(oldAssetFullInfo.getAssetTypeName());
            content.append("的资产信息");

            EmailNotifyTemplate emailNotifyTemplate = NotifyUtils.createEmailNotifyTemplate(notifyUsers, content.toString(), "小焱资管", "资产信息变更通知");

            rabbitTemplate.convertAndSend(RabbitmqConstants.EXCHANGE, RabbitmqConstants.EMAIL_ROUTINGKEY,emailNotifyTemplate);
        }
        return success("修改成功！");
    }

    @GetMapping("/getAssetsInfoByAddressId")
    @ApiOperation("根据资产位置id获取资产信息")
    public AjaxResult getAssetsInfoByAddressId(@RequestParam(value = "addressId", required = true) Long addressId) {
        List<AssetInfoView> list = assetInfoViewService.list(new QueryWrapper<AssetInfoView>().eq(AssetInfoView.ADDRESS_ID, addressId).orderByDesc(AssetInfoView.UPDATE_TIME));
        return AjaxResult.success(list);
    }

    @PostMapping("/uploadAssetImage")
    @ApiOperation("上传资产图片")
    public R<SysFile> uploadAssetImage(@RequestPart(value = "file") MultipartFile file) {
        R<SysFile> upload = fileController.upload(file, "asset/image");
        if (R.FAIL == upload.getCode()) {
            throw new ServiceException(upload.getMsg());
        }
        return upload;
    }

    @GetMapping("/assetResovleRecord")
    @ApiOperation(value = "查看资产处理记录", response = AssetResovleRecordVo.class)
    public AjaxResult assetResovleRecord(@RequestParam("assetId") Long assetId,
                                         @RequestParam(value = "type", required = false) Integer type)
    {
        List<AssetResovleRecordVo> result = new ArrayList<>();

        //查询用户、资产、部门、资产类型、资产地址数据
        CompletableFuture<R<Map<Long, SysUser>>> future1 = CompletableFuture.supplyAsync(() ->
                userController.getAllUsers());

        CompletableFuture<R<Map<Long, SysDept>>> future2 = CompletableFuture.supplyAsync(() ->
                deptController.getAllDeptsMap());

        R<Map<Long, SysUser>> allUsers = new R<>();
        R<Map<Long, SysDept>> allDeptsMap = new R<>();

        try {
            allUsers = future1.get();
            if (allUsers.getCode() == R.FAIL) {
                return AjaxResult.error("系统异常，请联系管理员");
            }
            allDeptsMap = future2.get();
            if (allDeptsMap.getCode() == R.FAIL) {
                return AjaxResult.error("系统异常，请联系管理员");
            }

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        Map<Long, SysUser> userMap = allUsers.getData();
        Map<Long, SysDept> deptMap = allDeptsMap.getData();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy.MM.dd");
        AsmsAssetFullInfo asset = assetFullInfoService.getOne(new QueryWrapper<AsmsAssetFullInfo>()
                .eq(AsmsAssetFullInfo.ASSET_ID, assetId));
        String assetName = asset.getAssetTypeName();

        //资产领用与退库
        List<AmsAssetRequisition> requisitions = assetRequisitionService
                .list(new QueryWrapper<AmsAssetRequisition>().eq(AmsAssetRequisition.ASSET_ID, assetId));
        if (requisitions.size() > 0) {
            for (AmsAssetRequisition requisition : requisitions) {
                //获取领用人
                SysUser user = userMap.get(requisition.getUserId());
                if (requisition.getRequisitionTime() != null) {
                    //表示该资产被领用
                    AssetResovleRecordVo vo1 = new AssetResovleRecordVo();
                    vo1.setResovleType("资产领用");
                    //获取领用处理人
                    SysUser sysUser = userMap.get(requisition.getChargerId());
                    if (sysUser != null) {
                        vo1.setResovler(sysUser.getNickName());
                    }
                    vo1.setResovleDateStr(fmt.format(new Date(requisition.getRequisitionTime())));
                    if (user != null && assetName != null) {
                        vo1.setResovleContent(user.getNickName() + "领用了" + assetName);
                        vo1.setOperUser(user.getNickName());
                    }
                    result.add(vo1);
                }
                if (requisition.getActualReturnTime() != null) {
                    //表示该资产已退库
                    AssetResovleRecordVo vo2 = new AssetResovleRecordVo();
                    vo2.setResovleType("资产退库");
                    //获取退库处理人
                    SysUser sysUser = userMap.get(requisition.getReturnChargerId());
                    if (sysUser != null) {
                        vo2.setResovler(sysUser.getNickName());
                    }
                    vo2.setResovleDateStr(fmt.format(new Date(requisition.getActualReturnTime())));
                    if (user != null && assetName != null) {
                        vo2.setResovleContent(user.getNickName() + "将资产：" + assetName + "退库了");
                        vo2.setOperUser(user.getNickName());
                    }
                    result.add(vo2);
                }
            }
        }

        //资产的借用归还记录
        List<AmsAssetBorrow> borrows = assetBorrowService
                .list(new QueryWrapper<AmsAssetBorrow>().eq(AmsAssetBorrow.ASSET_ID, assetId));
        if (borrows.size() > 0) {
            for (AmsAssetBorrow borrow : borrows) {
                //获取借用人
                SysUser user = userMap.get(borrow.getUserId());
                if (borrow.getBorrowTime() != null) {
                    //表示借用了资产
                    AssetResovleRecordVo vo3 = new AssetResovleRecordVo();
                    vo3.setResovleType("资产借用");
                    //获取借用处理人
                    SysUser sysUser = userMap.get(borrow.getChargerId());
                    if (sysUser != null) {
                        vo3.setResovler(sysUser.getNickName());
                    }
                    vo3.setResovleDateStr(fmt.format(new Date(borrow.getBorrowTime())));
                    if (user != null && assetName != null) {
                        vo3.setResovleContent(user.getNickName() + "借用了" + assetName);
                        vo3.setOperUser(user.getNickName());
                    }
                    result.add(vo3);
                }
                if (borrow.getActualReturnTime() != null) {
                    //表示归还了资产
                    AssetResovleRecordVo vo4 = new AssetResovleRecordVo();
                    vo4.setResovleType("资产归还");
                    //获取归还处理人
                    SysUser sysUser = userMap.get(borrow.getReturnChargerId());
                    if (sysUser != null) {
                        vo4.setResovler(sysUser.getNickName());
                    }
                    vo4.setResovleDateStr(fmt.format(new Date(borrow.getActualReturnTime())));
                    if (user != null && assetName != null) {
                        vo4.setResovleContent(user.getNickName() + "归还了" + assetName);
                        vo4.setOperUser(user.getNickName());
                    }
                    result.add(vo4);
                }
            }
        }

        //资产的调拨
        List<AmsAssetAllocationDetail> details = assetAllocationDetailService
                .list(new QueryWrapper<AmsAssetAllocationDetail>().eq(AmsAssetAllocationDetail.ASSET_ID, assetId));
        HashSet<Long> allocationIds = new HashSet<>();
        details.forEach(item -> allocationIds.add(item.getAllocationId()));
        List<AmsAssetAllocation> allocations = new ArrayList<>();
        if (allocationIds.size() > 0) {
            allocations = assetAllocationService.list(new QueryWrapper<AmsAssetAllocation>()
                    .in(AmsAssetAllocation.ALLOCATION_ID, allocationIds));
        }
        if (allocations.size() > 0) {
            for (AmsAssetAllocation allocation : allocations) {

                if (allocation.getInTime() != null) {
                    //表示调入了资产
                    AssetResovleRecordVo vo5 = new AssetResovleRecordVo();
                    vo5.setResovleType("资产调入");
                    SysUser sysUser = userMap.get(allocation.getInUserId());
                    SysDept sysDept = deptMap.get(allocation.getInDeptId());
                    if (sysUser != null && sysDept != null) {
                        vo5.setResovler(sysUser.getNickName());
                        vo5.setOperUser(sysUser.getNickName());
                        vo5.setResovleContent(sysUser.getNickName() + "调入了"
                                + assetName + "到" + sysDept.getDeptFullName() + "中");
                    }
                    vo5.setResovleDateStr(fmt.format(new Date(allocation.getInTime())));
                }
                if (allocation.getOutTime() != null) {
                    //表示调出了资产
                    AssetResovleRecordVo vo6 = new AssetResovleRecordVo();
                    vo6.setResovleType("资产调出");
                    vo6.setResovleDateStr(fmt.format(new Date(allocation.getOutTime())));
                    SysUser sysUser = userMap.get(allocation.getOutUserId());
                    SysDept sysDept = deptMap.get(allocation.getOutDeptId());
                    if (sysUser != null && sysDept != null) {
                        vo6.setResovler(sysUser.getNickName());
                        vo6.setOperUser(sysUser.getNickName());
                        vo6.setResovleContent(sysUser.getNickName() + "将" + assetName +
                                "从" + sysDept.getDeptFullName() + "中调出");
                    }
                }
            }
        }

        //实物信息变更
        List<AmsAssetInfoChange> changes = assetInfoChangeService.list(new QueryWrapper<AmsAssetInfoChange>()
                .eq(AmsAssetInfoChange.ASSET_ID, assetId));
        HashSet<Long> changeIds = new HashSet<>();
        changes.forEach(item -> changeIds.add(item.getAssetInfoChangeId()));
        List<AmsAssetInfoChangeDetail> changeDetails = new ArrayList<>();
        if (changeIds.size() > 0) {
            changeDetails = assetInfoChangeDetailService.list(new QueryWrapper<AmsAssetInfoChangeDetail>()
                    .in(AmsAssetInfoChangeDetail.ASSET_INFO_CHANGE_ID, changeIds));
        }
        if (changes.size() > 0) {
            for (AmsAssetInfoChange change : changes) {
                AssetResovleRecordVo vo7 = new AssetResovleRecordVo();
                StringBuilder builder = new StringBuilder();
                vo7.setResovleType("资产信息变更");
                SysUser sysUser = userMap.get(change.getChargerId());
                if (sysUser != null) {
                    vo7.setResovler(sysUser.getNickName());
                    vo7.setOperUser(sysUser.getNickName());
                    builder.append(sysUser.getNickName()).append("变更了")
                            .append(assetName).append("资产的基本信息：");
                }
                if (change.getChangeTime() != null) {
                    vo7.setResovleDateStr(fmt.format(new Date(change.getChangeTime())));
                }
                for (AmsAssetInfoChangeDetail changeDetail : changeDetails) {
                    if (changeDetail.getAssetInfoChangeId().equals(change.getAssetInfoChangeId())) {
                        builder.append(changeDetail.getAttribute()).append("由")
                                .append(changeDetail.getOldValue()).append("变成了")
                                .append(changeDetail.getNewValue()).append(" ");
                    }
                }
                vo7.setResovleContent(builder.toString());
            }
        }

        //维保信息登记
        List<AmsAssetMaintenanceRecord> recordList = assetMaintenanceRecordService
                .list(new QueryWrapper<AmsAssetMaintenanceRecord>()
                        .select(AmsAssetMaintenanceRecord.CHANGE_TIME, AmsAssetMaintenanceRecord.CHANGE_USER_ID)
                        .eq(AmsAssetMaintenanceRecord.ASSET_ID, assetId));
        if (recordList.size() > 0) {
            for (AmsAssetMaintenanceRecord record : recordList) {
                AssetResovleRecordVo vo8 = new AssetResovleRecordVo();
                vo8.setResovleType("资产维保信息登记");
                vo8.setResovleDateStr(fmt.format(new Date(record.getChangeTime())));
                //获取维保信息登记处理人
                SysUser sysUser = userMap.get(record.getChangeUserId());
                if (sysUser != null) {
                    vo8.setResovler(sysUser.getNickName());
                    vo8.setOperUser(sysUser.getNickName());
                    vo8.setResovleContent(sysUser.getNickName() + "登记了" + assetName + "的维保信息");
                }
            }
        }

        //维修信息登记
        List<AmsAssetRepairRecordDetail> recordDetails = assetRepairRecordDetailService
                .list(new QueryWrapper<AmsAssetRepairRecordDetail>().eq(AmsAssetRepairRecordDetail.ASSET_ID, assetId));
        HashSet<Long> repairRecordIds = new HashSet<>();
        recordDetails.forEach(item -> repairRecordIds.add(item.getRepairRecordId()));
        List<AmsAssetRepairRecord> repairRecords = new ArrayList<>();
        if (repairRecordIds.size() > 0) {
            repairRecords = assetRepairRecordService
                    .list(new QueryWrapper<AmsAssetRepairRecord>()
                            .in(AmsAssetRepairRecord.REPAIR_RECORD_ID, repairRecordIds));
        }
        if (repairRecords.size() > 0) {
            for (AmsAssetRepairRecord repairRecord : repairRecords) {
                AssetResovleRecordVo vo9 = new AssetResovleRecordVo();
                vo9.setResovleType("资产维修信息登记");
                if (repairRecord.getBusinessTime() != null) {
                    vo9.setResovleDateStr(fmt.format(new Date(repairRecord.getBusinessTime())));
                }
                vo9.setResovler(repairRecord.getResovleUser());
                vo9.setOperUser(repairRecord.getResovleUser());
                vo9.setResovleContent(repairRecord.getResovleUser() + "维修了" + assetName);
            }
        }

        //资产的清理报废
        List<AmsAssetScrapDetail> scrapDetails = assetScrapDetailService.list(new QueryWrapper<AmsAssetScrapDetail>()
                .eq(AmsAssetScrapDetail.ASSET_ID, assetId));
        HashSet<Long> assetScrapIds = new HashSet<>();
        scrapDetails.forEach(item -> assetScrapIds.add(item.getScrapId()));
        List<AmsAssetScrap> assetScraps = new ArrayList<>();
        if (assetScrapIds.size() > 0) {
            assetScraps = assetScrapService.list(new QueryWrapper<AmsAssetScrap>()
                    .in(AmsAssetScrap.SCRAP_ID, assetScrapIds));
        }
        if (assetScraps.size() > 0) {
            for (AmsAssetScrap assetScrap : assetScraps) {
                AssetResovleRecordVo vo10 = new AssetResovleRecordVo();
                vo10.setResovleType("资产清理报废");
                if (assetScrap.getScrapTime() != null) {
                    vo10.setResovleDateStr(fmt.format(new Date(assetScrap.getScrapTime())));
                }
                SysUser sysUser = userMap.get(assetScrap.getScrapUserId());
                if (sysUser != null) {
                    vo10.setResovler(sysUser.getNickName());
                    vo10.setOperUser(sysUser.getNickName());
                    vo10.setResovleContent(assetName + "已报废");
                }
            }
        }

        //将处理记录按处理时间进行降序排列
        result.sort(Comparator.comparing(AssetResovleRecordVo::getResovleDateStr).reversed());
        return AjaxResult.success(result);
    }
}
